import axios from "axios";
// import router from "@/router/routers";
import store from "@/store";
import { getToken, getAccount } from "@/utils/auth";
import { SUCCESS, ERROR_CODE_INTOKEN_ERROR } from "@/utils/constant";
import Config from "@/settings";
import Qs from "qs";

// improt alert solve scheme
import Message from "@/utils/message";
let showMessage = new Message();

// prompt message
const promptMessage = (message, type = "error") => {
  return showMessage.error({
    message,
    type,
    duration: 5 * 1000,
    offset: 80,
  });
};

// create axios examples
const service = axios.create({
  baseURL:
    process.env.NODE_ENV === "production"
      ? process.env.VUE_APP_BASE_API
      : "/api",
  timeout: Config.timeout,
});

// request 拦截器
service.interceptors.request.use(
  (config) => {
    if (getToken()) {
      config.headers["Authorization"] = getToken();
    }
    if (config.method === "post") {
      config.headers["Content-Type"] = "application/x-www-form-urlencoded";
      config.data = Qs.stringify(config.data);
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// response 拦截器
service.interceptors.response.use(
  (res) => {
    let {
      data: { code, message },
    } = res;
    if (code !== SUCCESS) {
      if (code === ERROR_CODE_INTOKEN_ERROR) {
        if (getAccount()) {
          // token过期，开始自动登录
          store
            .dispatch("user/AutoLogin") // 这里 dispatch 不一定会成功，接口没有上线，导致并没有进行测试，不确定 store 能否发送成功
            .then(() => {
              // 自动登录成功，刷新页面
              location.reload();
            })
            .catch(() => {
              // 登录失败，删除用户信息，提醒手动登录
              store.dispatch("DeleteInfo");
              promptMessage("登录认证已过期，请重新登录😋", "warning");
            });
        } else {
          // 第一次进入网站，没有登录过的用户
          promptMessage("登录后解锁更多功能😋", "warning");
        }
      } else {
        // 不是失败错误码 0，也不是token无效状态码，直接将其抛错
        promptMessage("Error " + message || "Error " + code);
      }
    }
    return res.data;
  },
  (error) => {
    let { message } = error;
    if (message.indexOf("timeout of") !== -1) {
      promptMessage("网络请求超时");
    } else if (message.indexOf("Network Error") !== -1) {
      promptMessage("网络出错，请检查连接");
    } else {
      promptMessage("faile: " + message);
    }
    return Promise.reject(new Error("faile: " + error));
  }
);

export default service;
